﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectCommonLibs.repository
{
    public class FileRepository
    {
        private readonly string rootDir;
        private List<string> oldFileNames;
        public FileRepository(string rootDir,string oldFileName = null)
        {
            this.rootDir = rootDir;
            oldFileNames = new List<string>();
            if (oldFileName != null)
            {
                oldFileNames.AddRange(getOldFileNames(oldFileName));
            }
        }
        public List<string> getNewFiles()
        {
            //用递归，来查找出所有文件
            newFileNames.Clear();
            getFileNames(rootDir);
            var diffFiles = newFileNames.Except(oldFileNames).ToList();
            oldFileNames.AddRange(diffFiles);
            return diffFiles;
        }

        private List<string> newFileNames = new List<string>();
        private void getFileNames(string currentDir)
        {
            try
            {
                var fileNames = Directory.GetFiles(currentDir).ToList();
                fileNames = fileNames.Where(name => name.EndsWith(".xlsx") || name.EndsWith(".xls")).ToList();
                newFileNames.AddRange(fileNames);
                var dirs = Directory.GetDirectories(currentDir).ToList();
                dirs.ForEach(dir => getFileNames(dir));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }

        public string[] getOldFileNames(string fileName)
        {
            List<string> oldFiles = new List<string>();
            try
            {
                if (File.Exists(fileName))
                {
                    return File.ReadAllLines(fileName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            return oldFiles.ToArray();
        }
    }
}
